package com.zf.mall.common.util;

import cn.hutool.core.date.DateUnit;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import cn.hutool.core.util.StrUtil;


import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 功能描述
 *
 * @description:    APP登录Token的生成和解析
 * @date: 2019/3/30 15:14
 */
public class JwtTokenUtil {

    /**
     * token秘钥，请勿泄露，请勿随便修改 backups:JKKLJOoadsafa
     */
    public static final String SECRET = "JKKLJOoadsDFIjfDIFDinmmjfdDafa";

    /**
     * token 过期时间: 100天
     * 本项目TOKEN将会在服务端 REDIS中保存，所以这个100天代表永不过期，真证的过期时间将会在REDIS中设置
     */
    public static final int calendarField = Calendar.DATE;
    public static final int calendarInterval = 100;

    /**
     * JWT生成Token.<br/>
     * <p>
     * JWT构成: header, payload, signature
     * @param user_id 登录成功后用户user_id, 参数user_id不可传空
     */

    public static String createToken(int field  , int expires , Long user_id) throws Exception {
        Date iatDate = new Date();
        // expire time
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(field, expires);
        Date expiresDate = nowTime.getTime();
        // header Map
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");

        // build token
        // param backups {iss:Service, aud:APP}
        String token = JWT.create().withHeader(map) // header
                .withClaim("iss", "Service") // payload
                .withClaim("aud", "APP")
                .withClaim("user_id", null == user_id ? null : user_id.toString())
                .withIssuedAt(iatDate) // sign time
                .withExpiresAt(expiresDate) // expire time
                .sign(Algorithm.HMAC256(SECRET)); // signature

        return token;
    }


    public static String createToken(Long user_id) throws Exception {
        Date iatDate = new Date();
        // expire time
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(calendarField, calendarInterval);
        Date expiresDate = nowTime.getTime();
        // header Map
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");

        // build token
        // param backups {iss:Service, aud:APP}
        String token = JWT.create().withHeader(map) // header
                .withClaim("iss", "Service") // payload
                .withClaim("aud", "APP").withClaim("user_id", null == user_id ? null : user_id.toString())
                .withIssuedAt(iatDate) // sign time
                .withExpiresAt(expiresDate) // expire time
                .sign(Algorithm.HMAC256(SECRET)); // signature

        return token;
    }


    /**
     * 解密Token
     * @param token
     * @return
     * @throws Exception
     */
    public static Map<String, Claim> verifyToken(String token) {
        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            jwt = verifier.verify(token);
        } catch (Exception e) {
            e.printStackTrace();
            // e.printStackTrace();
            // token 校验失败, 抛出Token验证非法异常
            //过期异常
        }
        return jwt.getClaims();
    }


    /**
     * 根据Token获取user_id
     * @param token
     * @return user_id
     */
    public static Long getAppUID(String token) {
        Map<String, Claim> claims = verifyToken(token);
        Claim user_id_claim = claims.get("user_id");
        if (null == user_id_claim || StrUtil.isEmpty(user_id_claim.asString())) {
            // token 校验失败, 抛出Token验证非法异常
        }
        return Long.valueOf(user_id_claim.asString());
    }


    public static void main(String[] args) {
        Long user = 112334L;
        int exp = 3;

        try {
            String token = createToken(Calendar.MINUTE,exp,user);
            System.out.println(token);


            SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间
            sdf.applyPattern("yyyy-MM-dd HH:mm:ss a");// a为am/pm的标记
            Date date = new Date();// 获取当前时间
            System.out.println("  现在时间：" + sdf.format(date));
            System.out.println(token );

            //date time :2021-09-07 11:32:55
            //token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJBUFAiLCJ1c2VyX2lkIjoiMTEyMzM0IiwiaXNzIjoiU2VydmljZSIsImV4cCI6MTYzOTYyNTk0NCwiaWF0IjoxNjMwOTg1OTQ0fQ.6jvxxNgFzgWCsu-UK_KY7Se_UgBLaIG5-ZISBg2BMd0";
           token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJBUFAiLCJ1c2VyX2lkIjoiMTEyMzM0IiwiaXNzIjoiU2VydmljZSIsImV4cCI6MTYzMDk4ODgxMywiaWF0IjoxNjMwOTg4NjMzfQ.kRXM_2Tzxo_HQglnN4LrjwxzcxK4A2OBjTmo10sgvIQ";

            Map<String, Claim> map = verifyToken(token);

            for(Map.Entry<String, Claim> entry : map.entrySet()){
                if(entry.getValue().asDate() != null){
                    System.out.println("Key = "+entry.getKey()+",value="+ sdf.format(entry.getValue().asDate()));
                }else{
                    System.out.println("Key = "+entry.getKey()+",value="+ entry.getValue().asString());
                }

            }



           // System.out.println(JSONObject.toJSONString(map));

            Long u = getAppUID(token);

            //System.out.println(u);

        }catch (Exception e){
            e.printStackTrace();
        }




    }

}